import { apiAndPCType, apiType, Box3Post, escapeHtml } from "@ap/util/request";
import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { auth } from "@ap/util/request";
import { updatePackageJson } from "@ap/util/packageJson";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import { CommandId, expandMap } from "@ap/command";
import insertCode from "@ap/util/vscode/insertCode";
import getFilePath from "@ap/util/vscode/getFilePath";

export let mapLish: ExtendedQuickPickItem[] = [];
export let isMapLish: boolean = false;

export function setIsMapLish(is: boolean) {
  isMapLish = is;
}
/**
 * 物品接口，扩展了共享的物品属性，添加了描述和ID。
 */
interface Item {
  reason: any;
  name: string;
  describe: string;
  id: string;
  playHash: string;
  editHash: string;
  subMaps: Record<string, any>;
  auditStatus: number;
  publishedVersionId: number | null;
}

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  id?: number;
  name?: string;
  subMaps: Record<string, any>[];
  playHash: any; // 游玩端Hash
  editHash: string; // 编辑端Hash
  auditStatus: number;
  publishedVersionId: number | null;
  reason: string[] | null;
}

export interface ExtendedQuickPickItem2 extends vscode.QuickPickItem {
  type: number;
}

/**
 * 请求选项配置，定义了获取内容列表的API请求参数。
 */
const requestOptions = {
  url: "ugc/creator/content/page",
  data: {
    title: "",
    type: 1,
    limit: 99,
    offset: 0,
    orderBy: 1,
    orderDesc: true,
  },
};

/**
 * 异步获取扩展地图列表数组。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function getBox3MapList(): Promise<ExtendedQuickPickItem[]> {
  /**
   * 发送请求并等待响应。
   */
  const response = await Box3Post(requestOptions, "扩展地图");
  /**
   * 检查响应是否成功，如果不成功则返回错误消息。
   */
  if (!response || response.code !== 200) {
    showErrorMessage(`获取扩展地图失败: ${response?.msg}`);
    return [];
  }
  /**
   * 处理响应数据，映射物品到数据项格式，并转义HTML字符以防止XSS攻击。
   */
  const dataSource: ExtendedQuickPickItem[] = response.data.rows.map(
    (item: Item) => ({
      label: `${escapeHtml(item.name.trim())}`,
      description: item.id.toString(),
      editHash: item.editHash,
      playHash: item.playHash,
      detail: `${escapeHtml(item.describe)}`,
      subMaps: item.subMaps,
      auditStatus: item.auditStatus,
      publishedVersionId: item.publishedVersionId,
      reason: item.reason,
    }),
  );
  mapLish = dataSource;
  expandMap.description = `共${dataSource.length}项`;
  return mapLish;
}

export default async function selectBox3Map() {
  if (!auth) {
    showErrorMessage(arenaErrorMsg.LOG_IN_TO_THE_SHINJIMA_ACCOUNT);
    vscode.commands.executeCommand(CommandId.userCenterTool_setting);
    return arenaErrorMsg.LOG_IN_TO_THE_SHINJIMA_ACCOUNT;
  }
  // 获取工作区的文件夹的路径。
  const workspaceFolder = getFilePath();
  // 如果没有找到工作区文件夹，则终止执行
  if (!workspaceFolder) {
    showInformationMessage(arenaErrorMsg.OPEN_WORKSPACE);
    vscode.commands.executeCommand(CommandId.ap_files_focusFilesExplorer);
    return arenaErrorMsg.OPEN_WORKSPACE;
  }

  try {
    const dataSource = await getBox3MapList();
    if (!dataSource) {
      return arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST;
    }
    if (!dataSource.length) {
      showErrorMessage(arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST);
      return arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST;
    }
    const selectedOption = await vscode.window.showQuickPick(dataSource, {
      title: "ArenaPro：链接扩展地图到本地项目",
      matchOnDescription: true,
      canPickMany: false,
    });

    if (selectedOption) {
      if (selectedOption.subMaps.length === 1) {
        const result = await updatePackageJson("map", {
          id: selectedOption.description,
          editHash: selectedOption.editHash,
          playHash: selectedOption.playHash,
        });
        if (result) {
          refres();
          showInformationMessage(`已链接到扩展地图: ${selectedOption.label}`);
          vscode.commands.executeCommand(CommandId.map_resource);
          return selectedOption;
        }
        return arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST;
      } else {
        const result = await selectBox3AffiliateMap(
          selectedOption.label,
          selectedOption.subMaps,
        );
        return result;
      }
    }
  } catch (error) {
    // 处理可能的用户取消操作或其他异常
    showErrorMessage(`选择操作遇到错误: ${error}`);
    return error;
  }
}

async function selectBox3AffiliateMap(
  label: string,
  subMaps: Record<string, any>,
) {
  try {
    const dataSource: ExtendedQuickPickItem[] = subMaps.map((item: Item) => ({
      label: `${escapeHtml(item.name)}`,
      description: item.id.toString(),
      editHash: item.editHash,
      playHash: item.playHash,
    }));

    const selectedOption = await vscode.window.showQuickPick(dataSource, {
      title: "ArenaPro：链接扩展地图到本地项目",
      placeHolder: "选择《" + label + "》的主附地图",
      matchOnDescription: true,
      canPickMany: false,
    });

    if (selectedOption) {
      const result = await updatePackageJson("map", {
        id: selectedOption.description,
        editHash: selectedOption.editHash,
        playHash: selectedOption.playHash,
      });
      if (result) {
        refres();
        showInformationMessage(`已链接到扩展地图: ${selectedOption.label}`);
        vscode.commands.executeCommand(CommandId.map_resource);
        return selectedOption;
      }
      return arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST;
    }
  } catch (error) {
    // 处理可能的用户取消操作或其他异常
    showErrorMessage(`选择操作遇到错误: ${error}`);
    return error;
  }
}

export async function selectBox3MapExpandDetail(map: ExtendedQuickPickItem) {
  try {
    if (map.name) {
      map.label = map.name;
    }
    let reason = "";
    if (map.reason) {
      for (const item of map.reason) {
        reason += item + "\n";
      }
    }
    const dataSource: ExtendedQuickPickItem2[] = [
      {
        label: `插入地图ID`,
        type: 1,
      },
      {
        label: `进入创作端`,
        type: 2,
      },
      {
        label: `复制游玩端直链`,
        type: 3,
      },
    ];
    const selectedOption = await vscode.window.showQuickPick(dataSource, {
      title: `《${map.label.trim()}》扩展地图操作`,
      placeHolder: reason,
      matchOnDescription: true,
      canPickMany: false,
    });

    if (selectedOption) {
      if (selectedOption.type === 1) {
        insertCode(map.description ?? String(map.id) ?? "");
      }
      if (selectedOption.type === 2) {
        vscode.commands.executeCommand(
          CommandId.map_showMap,
          map.editHash,
          map.label.trim(),
        );
      }
      if (selectedOption.type === 2) {
        vscode.env.clipboard.writeText(
          apiAndPCType[apiType].pc + "play/" + map.playHash,
        );
      }
    }
  } catch (error) {
    // 处理可能的用户取消操作或其他异常
    showErrorMessage(`选择操作遇到错误: ${error}`);
  }
}

function refres() {
  vscode.commands.executeCommand(CommandId.map_treeDataMapPhotoRefresh);
  vscode.commands.executeCommand(CommandId.map_treeDataMapModelsRefresh);
  vscode.commands.executeCommand(CommandId.map_treeDataMapTempChatEditRefresh);
}
